#Alexander F. Gazmararian
#afg2@princeton.edu

library(tidyverse)
library(modelsummary)
library(lmtest)
library(sandwich)
library(kableExtra)
library(margins)

source("code/fun/book_theme.r")
source("code/fun/savefig.r")
source("code/fun/fix_txt.r")
source("code/fun/coefnames4tables.r")

# Load CivicPulse data
cp <- readRDS("data/CivicPulse_Public.rds")

# Load caps data
caps <- readRDS("data/NatCAPS_20220928.rds")

# Process and merge data
caps$sample <- "National"
cp$sample <- ifelse(cp$Sample == "Standard", "Policymaker (National)", "Policymaker (Fossil Fuels)")
cp$weights <- cp$Weight_1
history <- rbind(subset(caps, select = c(History,weights,sample)), subset(cp, select = c(History,weights,sample)))

# Create figure 3.6----

history.plot <-
  history %>%
  filter(!is.na(History)) %>%
  group_by(History, sample) %>%
  summarise(n = sum(weights)) %>%
  group_by(sample) %>%
  mutate(pct = prop.table(n)) %>%
  ggplot(aes(x=History,y=pct,fill=sample,label=scales::percent(pct, accuracy = 1))) +
  geom_col(position="dodge") +
  geom_text(position = position_dodge(.9), vjust = -.5, size = 3) +
  scale_y_continuous(labels = scales::percent, expand = c(0,0), limits = c(0,.85)) +
  scale_x_discrete(labels = scales::label_wrap(25)) +
  scale_fill_grey(name = "") +
  labs(x = "", y = "") +
  book_theme +
  theme(
    legend.position = "bottom",
    legend.box.margin = margin(-25)
  )
history.plot
savefig(history.plot, "3.6_figure_promisehistory", height = 2, filepath = "figures/")

# Estimate linear models for online appendix ----

## NOTE: the following variables are only in the restricted access data (see README.txt): biden2020 + Census_area_college + log(Census_area_population) + Census_area_urban

# Specify models
f.base <- y ~ Age_cat + Woman + College + Minority_bin + PartySummary + Gov_type + biden2020 + Sample + Census_area_college + log(Census_area_population) + Census_area_urban
f.base.slim <- y ~ Age_cat + Woman + College + Minority_bin  + Gov_type +  Sample

ols.history <- list()
#local policymaker models
ols.history[[1]] <- lm(update(f.base.slim, History_scale ~ .), cp, weights = weights)
ols.history[[2]] <- lm(update(f.base, History_scale ~ .), cp, weights = weights)
ols.history[[3]] <- lm(update(f.base, History_scale ~ . + Investment_scale), cp, weights = weights)
#national public models
ols.history[[4]] <- lm(History_scale ~ age + Female + Black + Hispanic + CollegeDegree + PartySummary + rural, caps, weight = weights)

# create table
file <- "tables/ch3/ols_historypromises.txt"
modelsummary(
  ols.history,
  vcov = "HC2",
  stars = c("*"=.1,"**"=.05,"***"=.01),
  coef_map = coefnames,
  gof_map = c("nobs", "adj.r.squared"),
  escape=FALSE,
  output="latex"
) %>%
  add_header_above(c(" " = 1, "Local Policymakers:" = 3, "National:" = 1))
#  cat(., file = file)
#fix_txt(file)
